package com.ftd.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * Created by apple on 16/8/2.
 */
@Controller
@RequestMapping("/hibook")
public class EbookViewDetailController {
    @RequestMapping(value = "getEbookDetail/{title}.do", method = RequestMethod.GET)
    public ModelAndView getEbookDetail(@PathVariable String title,ModelAndView modelAndView) throws IOException {
        ResponseHandler<String> myHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(
                    final HttpResponse response) throws IOException {
                return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        };

        String content = Request.Get("http://apis.juhe.cn/goodbook/query?catalog_id=252&pn=1&rn=30&dtype=&key=f5094a267c16bde9818bb0da9fc26443").execute().handleResponse(myHandler);

        //content是json的一个对象,将其转换成String
        String jsonString = content;
        //讲json字符串转变成json对象
        JSONObject jsonObject = JSON.parseObject(jsonString);
        //获取json的result对象
        JSONObject resultObject = jsonObject.getJSONObject("result");
        //获取result对象里的data的json数组
        JSONArray jsonArray = resultObject.getJSONArray("data");

        for (int i = 0; i < jsonArray.size() ; i++) {
            if(jsonArray.getJSONObject(i).get("title").toString().equals(title)){
                System.out.println("是");
                String sub2 = jsonArray.getJSONObject(i).get("sub2").toString();
                String imageUrl = jsonArray.getJSONObject(i).get("img").toString();
                String title1 = jsonArray.getJSONObject(i).get("title").toString();

                modelAndView.addObject("sub2",sub2);
                modelAndView.addObject("imageUrl",imageUrl);
                modelAndView.addObject("title",title1);

                modelAndView.setViewName("ebookDetailView");
                return modelAndView;
            }
        }
        System.out.println("**************"+title);

//        System.out.println(content);
        return modelAndView;

    }
}
